//
//  UIImageView+utils.m
//  storeapp
//
//  Created by huangyi on 13-1-23.
//  Copyright (c) 2013年 ios. All rights reserved.
//

#import "UIImageView+utils.h"
#import "UIImage+utils.h"
#import "NSString+path.h"
#import "NSData+utils.h"
#import "NSString+hash.h"
#import <QuartzCore/QuartzCore.h>

#define CACHE_EXPIRE_TIME_INTERVAL 864000

@implementation UIImageView (utils)

-(void)imageFromURL:(NSString *)urlstring{
    [self imageFromURL:urlstring diskCache:NO];
}
-(void)imageFromURL:(NSString *)urlstring onComplete:(dispatch_block_t)block{
    [self imageFromURL:urlstring diskCache:NO onComplete:block];
}
-(void)imageFromURL:(NSString *)urlstring diskCache:(BOOL)cache{
    [self imageFromURL:urlstring diskCache:cache onComplete:nil];
}

+(NSString*)diskCacheForURL:(NSString*)urlstring{
    NSString *hash=urlstring.sha1.hexString;
    NSString *path=@"img".cachePath;
    NSString *filecache=[path stringByAppendingPathComponent:hash];
    return filecache;
}


-(void)imageFromURL:(NSString *)urlstring diskCache:(BOOL)cache onComplete:(dispatch_block_t)block{
    UIImage *image=nil;
    NSString *hash=urlstring.sha1.hexString;
    NSString *path=@"img".cachePath;
    NSString *filecache=[path stringByAppendingPathComponent:hash];
    if (cache) {
        if (filecache.isFile) {
            NSDate *date=filecache.fileModificationDate;
            NSDate *now=[NSDate date];
            if ([now timeIntervalSinceDate:date]>CACHE_EXPIRE_TIME_INTERVAL) {
                [filecache removeFile];
            }
        }
        if (filecache.isFile) {
            NSData *data=[NSData dataWithContentsOfFile:filecache];
           image=[UIImage imageWithData:data];
            if (image==nil) {
                [filecache removeFile];
            }
        }
    }
    if (image!=nil) {
        self.image=image;
        if (block) {
            block();
        }
        return;
    }
    self.image=nil;
    UIColor *backgroundColor=self.backgroundColor;
    self.backgroundColor=[UIColor clearColor];
    UIActivityIndicatorView *activity=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self addSubview:activity];
    activity.layer.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.3].CGColor;
    activity.layer.cornerRadius=5;
    float size=MIN(MIN(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)), MIN(CGRectGetWidth(activity.frame), CGRectGetHeight(activity.frame)));
    activity.frame=CGRectMake(0, 0, size, size);
    activity.center=CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
    activity.autoresizingMask=UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleLeftMargin;
    NSURL *url=[NSURL URLWithString:urlstring];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    static NSOperationQueue *queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue=[[NSOperationQueue alloc] init];
    });
    [activity startAnimating];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [activity stopAnimating];
            [activity removeFromSuperview];
            self.backgroundColor=backgroundColor;
            UIImage *image=[UIImage imageWithData:data];
            if (!image) {
                if (filecache.isFile) {
                    [filecache removeFile];
                }
            }else{
                [filecache write:data];
            }
            self.image=image;
            if (block) {
                block();
            }
        });
    }];
}

@end
